package com.smallkingson.ylib.core.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;


public class YStrings {

	public static boolean isNull(String s) {

		if (s == null) {
			return true;
		}
		if (s.trim().equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 1月3日 格式化成01月03日
	 * 
	 * @param time
	 * @return
	 */
	public static String formatTime(int time) {

		String timeStr = "" + time;
		if (timeStr.length() < 2) {
			timeStr = "0" + timeStr;
		}
		return timeStr;
	}

	/**
	 * 把秒数转成当前时间
	 */
	public static String formatSecond(int second) {

		int hour = 0, minute = 0;

		if (second >= 60) {

			minute = second / 60;
			second = second % 60;
			if (minute > 60) {
				hour = minute / 60;
				minute = minute % 60;
			}
		}
		return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second);

	}

	public static String replaceAll(String str, String regex, String newStr) {

		for (String old : YPatterns.findMatchStrArr(str, regex)) {
			str = str.replace(old, newStr);
		}
		return str;
	}

	/**
	 * 
	 * @param str
	 * @param s
	 *            要匹配的字符串
	 * @param diJiGe
	 *            第几次出现
	 * @return
	 */
	public static int indexOf(String str, String s, int diJiGe) {

		int index = 0;
		int sum = -1;
		for (int i = 0; i < diJiGe; i++) {
			index = str.indexOf(s);
			str = str.substring(index + 1);
			sum += index;
			if (index > -1 && i == 0) {
				sum += 2;
			}
		}
		return sum;
	}

	public static String md5(String str) {

		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	public static String formatTimeStamp(long timeStamp, String format) {

		return new SimpleDateFormat(format).format(timeStamp);

	}
	public static String byteArray2hex(byte[] buffer) {

		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < buffer.length; i++) {
			builder.append(" ");
			String temp = Integer.toHexString(buffer[i]);
			if (temp.length() == 1) {
				builder.append("0").append(temp);
			} else {
				builder.append(temp);
			}
		}
		return builder.toString();
	}
}
